package com.wyd.jwpkglxt_ssm.controller;

import com.wyd.jwpkglxt_ssm.entity.CourseSystem;
import com.wyd.jwpkglxt_ssm.service.CourseSystemService;
import com.wyd.jwpkglxt_ssm.util.ResultCode;
import com.wyd.jwpkglxt_ssm.util.ResultUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * (CourseSystem)表控制层
 *
 * @author wyd
 * @since 2021-08-09 23:06:34
 */
@RestController
@RequestMapping("courseSystem")
public class CourseSystemController {

    // 取出属性文件中的值
    @Value("${baseDir}")
    private String baseDir;

    /**
     * 服务对象
     */
    @Autowired
    private CourseSystemService courseSystemService;

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("selectOne")
    public CourseSystem selectOne(Integer id) {
        return this.courseSystemService.queryById(id);
    }

    @GetMapping("courseSystem/page")
    public ResultUtil getAllDepartmentByPage(Integer pageNum, Integer pageSize,
                                             @RequestParam(required = false)String fileName,
                                             @RequestParam(required = false)String extensionName) {
        CourseSystem courseSystem = new CourseSystem().setFileName(fileName).setExtensionName(extensionName);
        return ResultUtil.ok().data("pageInfo",this.courseSystemService.queryAllByPage(pageNum,pageSize,courseSystem));
    }

    @PostMapping("courseSystem")
    public ResultUtil uploadCourseSystem(@RequestParam(value = "file",required = false) CommonsMultipartFile file,
                                         CourseSystem courseSystem) throws IOException {
        //for(int i =0;i<fileList.length;i++){
        //    String uploadOriginalFileName = fileList[i].getOriginalFilename();
        //    int i = uploadOriginalFileName.lastIndexOf(".");
        //    if(i!=-1){
        //        String uploadFileExtensionName = uploadOriginalFileName.substring(i).trim();
        //        String uploadFileName = uploadOriginalFileName.substring(0,i).trim();
        //    }
        //}
        String uploadOriginalFileName = file.getOriginalFilename();
        if(uploadOriginalFileName!=null){
            int i = uploadOriginalFileName.lastIndexOf(".");
            String uploadFileExtensionName = uploadOriginalFileName.substring(i).trim();
            String uploadFileName = uploadOriginalFileName.substring(0,i).trim();
            this.courseSystemService.insert(new CourseSystem().setFileName(uploadFileName).setExtensionName(uploadFileExtensionName));
            String path = baseDir;
            File realPath = new File(path);
            if(!realPath.exists()){
                realPath.mkdirs();
            }
            file.transferTo(new File(path + "/" + uploadOriginalFileName));
            return ResultUtil.ok();
        }
        return ResultUtil.error(ResultCode.UNKNOWN_ERROR);
    }

    @GetMapping("courseSystem/{courseSystemId}")
    public void downloadCourseSystem(@PathVariable("courseSystemId") Integer id,HttpServletResponse response){
        if(id!=null){
            CourseSystem courseSystem = this.courseSystemService.queryById(id);
            FileInputStream fis = null;
            ServletOutputStream outputStream = null;
            try {
                String fileName = courseSystem.getFileName()+courseSystem.getExtensionName();
                // 1.设置response的响应头
                response.reset();
                response.setCharacterEncoding("utf-8");
                response.setContentType("multipart/form-data");//二进制传输数据
                // 2.设置响应头
                response.setHeader("Content-Disposition","attachment;fileName=" +
                        URLEncoder.encode(fileName,"utf-8"));

                File file = new File(baseDir+"/"+fileName);
                fis = new FileInputStream(file);
                outputStream = response.getOutputStream();

                byte [] buffer = new byte[1024];
                int len;
                while((len = fis.read(buffer))!= -1){

                    outputStream.write(buffer,0, len);
                    outputStream.flush();
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (FileNotFoundException e){
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                if(outputStream != null){
                    try {
                        outputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if(fis != null){
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

    }

    @DeleteMapping("courseSystem/{courseSystemId}")
    public ResultUtil deleteCourseSystemById(@PathVariable("courseSystemId")String ids){
        if(ids.contains("-")){
            String[] idsplit = ids.split("-");
            List<Integer> courseSystemIds = new ArrayList<>();
            for(String s : idsplit){
                courseSystemIds.add(Integer.parseInt(s));
            }
            boolean delCourseSystems = this.courseSystemService.deleteCourseSystemBatch(courseSystemIds);
            if(delCourseSystems){
                return ResultUtil.ok();
            }
        }else if(!"".equals(ids)){
            Integer id = Integer.parseInt(ids);
            boolean delCourseSystem = this.courseSystemService.deleteById(id);
            if(delCourseSystem){
                return ResultUtil.ok();
            }
        }
        return ResultUtil.error(ResultCode.UNKNOWN_ERROR);
    }

    @GetMapping("courseSystem/extension/name")
    public ResultUtil getAllExtensionName(){
        List<String> extensionNames = this.courseSystemService.queryAllExtensionName();
        if(!extensionNames.isEmpty()){
            return ResultUtil.ok().data("extensionNames",extensionNames);
        }
        return ResultUtil.error(ResultCode.UNKNOWN_ERROR);
    }
}